package com.wichell.framework.wechat.service;

import java.io.IOException;
import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import com.wichell.framework.wechat.bo.response.WechatAccessToken;
import com.wichell.framework.wechat.bo.response.WechatJsConfig;
import com.wichell.framework.wechat.bo.response.WechatOauth2AccessToken;
import com.wichell.framework.wechat.exception.WechatJsApiException;
import com.wichell.framework.wechat.exception.WechatMessageException;
import com.wichell.framework.wechat.exception.WechatRequestException;
import com.wichell.framework.wechat.util.AccessTokenUtils;
import com.wichell.framework.wechat.util.SignUtils;

@Service
public class WechatRequestService {

	private static final Logger _logger = Logger.getLogger(WechatRequestService.class);

	@Autowired
	private MessageHandler messageHandler;

	@Value("${wx.app.id}")
	private String appId;

	@Value("${wx.app.secret}")
	private String appSecret;

	@Value("${wx.app.token}")
	private String appToken;

	/**   
	 * @Title: getPublicAccessToken   
	 * @Description: 获取公众号的全局唯一接口调用凭据 
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: WechatAccessToken      
	 * @throws   
	 */
	public WechatAccessToken getPublicAccessToken() throws WechatRequestException {
		return AccessTokenUtils.getPublicAccessToken(appId, appSecret);
	}

	/**   
	 * @Title: getOauthAccessToken   
	 * @Description: 通过code换取网页授权access_token
	 * @param: @param code
	 * @param: @return
	 * @param: @throws WechatRequestException      
	 * @return: WechatOauth2AccessToken      
	 * @throws   
	 */
	public WechatOauth2AccessToken getOauthAccessToken(String code) throws WechatRequestException {
		return AccessTokenUtils.getOauthAccessToken(appId, appSecret, code);
	}

	/**   
	 * @Title: processRequest   
	 * @Description: processRequest
	 * @param: @param request
	 * @param: @return
	 * @param: @throws WechatMessageException      
	 * @return: String      
	 * @throws   
	 */
	public String processRequest(HttpServletRequest request) throws WechatMessageException {
		// 从request中取得输入流
		byte[] requestBody;
		try {
			requestBody = StreamUtils.copyToByteArray(request.getInputStream());
			String message = new String(requestBody, "UTF-8");

			if (_logger.isDebugEnabled()) {
				_logger.debug(MessageFormat.format("微信消息原始请求{0}：", message));
			}

			return messageHandler.handleCustomMessage(message);
		} catch (IOException e) {
			e.printStackTrace();
			throw new WechatMessageException(e.getMessage());
		}
	}

	/**   
	 * @Title: getJsApiConfig   
	 * @Description: 获取配置用于jsapi
	 * @param: @param url 当前url
	 * @param: @param publicToken 公共token
	 * @param: @param jsApiTicket jsapi票据
	 * @param: @return
	 * @param: @throws WechatJsApiException      
	 * @return: WechatJsConfig      
	 * @throws   
	 */
	public WechatJsConfig getJsApiConfig(String url, String jsApiTicket) throws WechatJsApiException {
		try {
			// 时间戳
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			// 随机字符串
			String noncestr = SignUtils.getRandomString();
			// 签名验证
			String signature = SignUtils.jsapiTicketSha1(MessageFormat.format(
					"jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsApiTicket, noncestr, timestamp, url));

			return new WechatJsConfig(appId, timestamp, noncestr, signature);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
